<style>
* {
   margin: 0px;
   padding: 0px;
}

.col-marleft {
   display: flex;
   justify-content: space-around;
}

.head_search {
   margin-bottom: 10px;
}
</style>

<template>
   <!-- 头部搜索 -->
   <div class="head_search">
      <el-row>
         <el-col :span="10">
            <!-- 打开添加弹窗 -->
            <el-button type="info" @click="dialogFormVisible = true" plain>
               <el-icon>
                  <Plus />
               </el-icon>添加
            </el-button>
            <!-- 批量删除 -->
            <el-button type="danger" @click="handleDelete(0, 0)" plain>
               <el-icon>
                  <Delete />
               </el-icon>批量删除
            </el-button>
         </el-col>
      </el-row>
   </div>

   <!-- 表格 -->
   <!-- 设置表格中的语言配置为中文 -->
   <el-config-provider :locale="zhCn">
      <el-table :data="tableData" style="width: 100%;" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" />
         <el-table-column label="编号" prop="id" />
         <el-table-column label="建筑物名" prop="building">
            <template #default>
               <span>门诊大楼</span>
            </template>
         </el-table-column>
         <el-table-column label="楼层" prop="floor" />
         <el-table-column label="创建时间" prop="create_time" />
         <el-table-column label="操作">
            <template #default="scope">
               <el-button size="small" type="primary" plain :icon="Edit" @click="handleEdit(scope.$index, scope.row)" />
               <el-button size="small" type="danger" plain :icon="Delete" @click="handleDelete(scope.$index, scope.row)" />
            </template>
         </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="demo-pagination-block" style="margin-top: 10px;">
         <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50, 100]"
            :small="small" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
   </el-config-provider>

   <!-- 添加/编辑Form -->
   <el-dialog v-model="dialogFormVisible" title="添加科室" :before-close="clearForm" :close-on-click-modal="false">
      <el-form :model="formInfo" :label-position="labelPosition" class="demo-form-inline">
         <!-- 建筑物名-->
         <el-row class="col-marleft">
            <el-col :span="24">
               <el-form-item label="建筑物名">
                  <el-select v-model="formInfo.building" placeholder="选择建筑物名">
                     <el-option label="门诊大楼" :value="1" />
                  </el-select>
               </el-form-item>
            </el-col>
         </el-row>

         <!-- 楼层-->
         <el-row class="col-marleft">
            <el-col :span="24">
               <el-form-item label="楼层">
                  <el-slider v-model="formInfo.floor" :min="-2" :max="20" vertical height="100px" />
               </el-form-item>
            </el-col>
         </el-row>

         <!-- 平面图-->
         <el-row class="col-marleft">
            <el-col :span="24">
               <el-form-item label="平面图">
                  <el-upload action="#" list-type="picture-card" :auto-upload="false" @change="changehaner">
                     <el-icon>
                        <Plus />
                     </el-icon>
                     <template #file="{ file }" v-if="showActions">
                        <div>
                           <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                           <span class="el-upload-list__item-actions">
                              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                 <el-icon><zoom-in /></el-icon>
                              </span>
                              <span v-if="!disableds" class="el-upload-list__item-delete" @click="handleDownload(file)">
                                 <el-icon>
                                    <Download />
                                 </el-icon>
                              </span>
                              <span v-if="!disableds" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                 <el-icon>
                                    <Delete />
                                 </el-icon>
                              </span>
                           </span>
                        </div>
                     </template>
                  </el-upload>

                  <el-dialog v-model="dialogVisible">
                     <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%; height: 100%;" />
                  </el-dialog>
               </el-form-item>
            </el-col>
         </el-row>
         <p>{{ formInfo.planurl }}</p>
      </el-form>
      <template #footer>
         <span class="dialog-footer">
            <el-button @click="clearForm">取消</el-button>
            <el-button type="primary" @click="btnSave">
               提交
            </el-button>
         </span>
      </template>
   </el-dialog>
</template>

<script setup >
import { computed, onMounted, ref, reactive, watch, defineProps, defineEmits } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox, ElConfigProvider, UploadFile } from 'element-plus'
// 引入中文包
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import * as qiniu from 'qiniu-js';
import { Delete, Edit, Search, Share, Upload, Add } from '@element-plus/icons-vue'
//存储服务器返回的所有数据
var tableData = ref([]);

//弹出窗状态
var dialogFormVisible = ref(false);

//设置楼层拉条
const value = ref(0);

//设置添加部门表单的input前文字
const labelPosition = ref('top');



//存储添加/编辑楼层信息
var formInfo = ref({
   id: 0,
   building: "",//建筑物名
   floor: 0,//楼层
   planurl: "",//平面图
   coordinfo: ""//楼层坐标数据
})

//页面加载完之后执行
onMounted(() => {
   bindData(pageSize.value, currentPage.value);
})

//分页
const currentPage = ref(1)//当前页数
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
const pageSize = ref(5)//每页条数
const total = ref(0)//总数据量

//切换每页条数
const handleSizeChange = (val) => {
   bindData(val, currentPage.value);
}

//切换页数
const handleCurrentChange = (val) => {
   bindData(pageSize.value, val);
}

//查询绑定数据
function bindData(page, pageNum) {
   axios.get(`/api/business/Foordata/list?PageNum=${pageNum}&PageSize=${page}&TotalNum=16&TotalPageNum=0`).then(function (res) {
      tableData.value = res.data.data.result;
      currentPage.value = res.data.data.pageIndex;
      total.value = res.data.data.totalCount;
   }).catch(() => {
      ElMessage({
         type: 'warning',
         message: "网络异常!"
      })
   });
}

//保存数据
function btnSave() {
   axios({
      url: "/api/business/Foordata",
      method: formInfo.value.id == 0 ? "post" : "put",
      data: formInfo.value,
      headers: {
         "Content-Type": "application/json"
      }
   }).then((res) => {
      var str = formInfo.value.id == 0 ? '添加' : '编辑'
      if (res.data.code == 200) {
         ElMessage({
            message: str + '成功',
            type: 'success',
         });
         clearForm();
         bindData(pageSize.value, currentPage.value);
      } else {
         ElMessage({
            message: str + '失败',
            type: 'warning',
         })
      }
   })
}

//清理表单并关闭弹窗
function clearForm() {
   dialogFormVisible.value = false;
   formInfo.value = {
      id: 0,
      building: "",//建筑物名
      floor: 0,//楼层
      planurl: "",//平面图
      coordinfo: ""//楼层坐标数据
   }

}


//编辑
var handleEdit = (index, row) => {
   formInfo.value = row;
   dialogFormVisible.value = true;
}

//存储选中的数据的id集合
const idArr = ref([]);


//获取表格多选按钮选中后的数据id集合
const handleSelectionChange = (val) => {
   idArr.value = val.map(item => item.id); // 获取选中行的id组成的数组，假设id是每一行的一个
}

//删除
var handleDelete = (index, row) => {
   var id;//删除数据的主键
   ElMessageBox.confirm(
      '确定要删除吗?',
      'Warning',
      {
         confirmButtonText: '确认',
         cancelButtonText: '取消',
         type: 'warning',
      }
   ).then(() => {
      id = row.id > 0 ? row.id : idArr.value.join(',');
      axios.delete(`/api/business/Foordata/${id}`).then(function (res) {
         // console.log(res);
         //返回格式：{code: 110, msg: "存在下级部门，不允许删除"}
         if (res.data.code == 200) {
            ElMessage({
               type: 'success',
               message: "删除成功"
            })
            bindData(pageSize.value, currentPage.value);
         } else {
            ElMessage({
               type: 'warning',
               message: "删除失败" + res.data.msg
            })
         }

      }).catch(() => {
         ElMessage({
            type: 'warning',
            message: "删除失败!"
         })
      })

   }).catch(() => {
      ElMessage({
         type: 'info',
         message: '用户取消操作',
      })
   })
}


//上传图片
var dialogImageUrl = ref('')
var dialogVisible = ref(false)
var disableds = ref(false)

var showActions = ref(true)

//移除
const handleRemove = (file) => {
   file.url = ''
   showActions.value = false;
}

//放大预览
const handlePictureCardPreview = (file) => {
   dialogImageUrl.value = file.url
   dialogVisible.value = true
}

//下载
const handleDownload = (file) => {
   console.log(file)
   console.log(file.url);
}



//上传图片到七牛云
function changehaner(e) {
   console.log(e);
   //console.log(fileinfo)
   // const file = e.target.files[0];
   const file = e.raw;
   console.log("file");
   console.log(file);
   //const file =fileinfo;

   const key = getNowDate() + file.name;
   ////获取七牛云token
   axios.get('http://8.130.174.200:8085/api/UploadImgToQiNiuYun/getToken').then((res) => {
      var token = res.data.token;
      const putExtra = {
         fname: '',
         params: {},
         mimeType: ['image/png', 'image/jpeg', 'image/jpg'],//要求上传的格式
      };
      const config = {
         useCdnDomain: true, //使用cdn加速
      };
      const observable = qiniu.upload(file, key, token, putExtra, config);
      console.log(observable);
      observable.subscribe({
         next: (result) => {
            // 主要用来展示进度
            console.warn(result);
         },
         error: (error) => {
            console.log(error)
         },
         complete: (res) => {
            console.log(res.key);
            // 生成图片路径
            const domain = 'http://s711x59qz.hd-bkt.clouddn.com'; // 替换为您的七牛云域名
            const imageURL = `${domain}/${res.key}`;
            console.log(imageURL);
            formInfo.value.planurl = imageURL;
         },
      });
   })
}
//获取当前时间，用于拼接上传图片的名称
function getNowDate() {
   const now = new Date();
   const year = now.getFullYear();
   const month = ('0' + (now.getMonth() + 1)).slice(-2);
   const day = ('0' + now.getDate()).slice(-2);
   const hours = ('0' + now.getHours()).slice(-2);
   const minutes = ('0' + now.getMinutes()).slice(-2);
   const seconds = ('0' + now.getSeconds()).slice(-2);
   return `${year}${month}${day}${hours}${minutes}${seconds}`;
}


</script>